import config from '@/request/baseUrl.js';
import request from '@/request/request.js';
import EventBus from "@/request/eventBus.js";
import {
  recordAdd,
  taskList,
  offlineCache,
  taskIncomplete
} from "@/request/task.js";
import {
  getAppVersion
} from "@/request/user.js";

// 上传图片 /common/upload
export const commonUpload = async (filePath, url = '/common/upload', name = 'file', address = '') => {
  const token = uni.getStorageSync('TOKEN')
  let position = ""; // 定位信息
  // #ifdef APP-PLUS
  position = address ? address : await getLocation();
  // #endif
  // #ifdef H5
  position = `H5不支持定位信息，仅供样式参考`;
  // #endif
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: config.baseUrl + url,
      filePath: filePath,
      formData: {
        position,
      },
      header: {
        Authorization: "Bearer " + token
      },
      name: name,
      success: (data) => {
        let info = JSON.parse(data.data)
        resolve(info);
      },
      fail: (e) => {
        uni.$uv?.throttle(() => {
          uni.showToast({
            title: '上传失败',
            icon: 'none',
            duration: 2000
          })
        }, 2000)
        reject(false);
      }
    });
  })
}

export const getLocation = () => {
  return new Promise((resolve) => {
    uni.getLocation({
      type: "gcj02",
      geocode: true,
      success: (res) => {
        if (res.address) {
          const {
            province,
            city,
            district,
            street,
            streetNum
          } = res.address;
          resolve(`${province}${city}${district}${street}${streetNum}`);
        }
      },
      fail: () => {
        resolve("定位失败");
      },
    });
  });
};

// 检测人脸
export const faceVerify = (data) => {
  return request({
    url: `/common/face/verify`,
    method: 'post',
    data,
  })
}

// 检测版本更新
export const uploadApp = (loading = false) => {
  if (loading) {
    uni.showLoading({
      title: "检查更新中...",
      icon: "none",
    });
  }
  let data = {
    // #ifdef APP-PLUS
    type: plus.os.name == "Android" ? "ANDROID" : "IOS",
    // #endif
    // #ifndef APP-PLUS
    type: "ANDROID",
    // #endif
    clientType: 1, // 客户端类型（1维保 2业主 3维修）
  }
  getAppVersion(data).then((res) => {
    if (res.code == 200) {
      let info = res.data;
      if (info) {
        // #ifdef APP-PLUS
        plus.runtime
          .getProperty(plus.runtime.appid, (app) => {
            setTimeout(() => {
              if (parseInt(info.version) > parseInt(app.versionCode)) {
                uni.hideLoading();
                uni.$emit("upgrade", info);
              } else {
                if (loading) {
                  uni.hideLoading();
                  uni.showToast({
                    title: "已是最新版本",
                    icon: "none",
                  });
                }
              }
            }, 1000);
          });
        // #endif
        // #ifndef APP-PLUS
        uni.getSystemInfo().then((res) => {
          setTimeout(() => {
            if (parseInt(info.version) > parseInt(res.appVersionCode)) {
              uni.hideLoading();
              uni.$emit("upgrade", info);
            } else {
              if (loading) {
                uni.hideLoading();
                uni.showToast({
                  title: "已是最新版本",
                  icon: "none",
                });
              }
            }
          }, 1000);
        });
        // #endif
      }
    }
  });
}

// 创建目录
export const createDirectory = (directoryPath, successCallback, failCallback) => {
  plus.io.resolveLocalFileSystemURL(directoryPath, (entry) => {
    // 如果目录已存在
    successCallback('目录已存在：' + entry.fullPath);
  }, (err) => {
    // 如果目录不存在，尝试创建
    plus.io.requestFileSystem(plus.io.PRIVATE_DOC, (fs) => {
      fs.root.getDirectory(directoryPath, {
        create: true
      }, (newEntry) => {
        successCallback('目录创建成功：' + newEntry.fullPath);
      }, (error) => {
        failCallback('创建目录失败：' + error.message);
      });
    }, (error) => {
      failCallback('请求文件系统失败：' + error.message);
    });
  });
}

// 获取任务缓存列表
export const taskCacheList = (subPlanId) => {
  taskList({ pageNum: 1, pageSize: 1000 }).then((res) => {
    if (res.code == 200) {
      uni.setStorageSync('offline-task-list', {
        subPlanId,
        data: res.rows,
        date: new Date().getTime(),
        frist: true, // 是否首次进入
        finish: false, // 是否完成
        offFinish: false // 是否离线完成
      });
    }
  })

  taskIncomplete(subPlanId).then((res) => {
    if (res.code == 200) {
      let statistics = {};
      res.data.forEach((item) => {
        let num = item.totalSum - item.completedCountSum;
        if (num > 0) {
          statistics[item.deviceId] = num;
        }
      })
      uni.setStorageSync('offline-task-device', statistics);
    }
  })

  offlineCache(subPlanId).then((res) => {
    if (res.code == 200) {
      // #ifdef H5
      uni.setStorageSync('offline-task-cache', res.data.slice(0, 2)); // 浏览器缓存限制，只缓存2条做测试
      // #endif
      // #ifdef APP-PLUS
      uni.setStorageSync('offline-task-cache', res.data);
      // #endif
    }
  })
}

// 清除任务缓存列表
export const clearTaskCache = () => {
  uni.removeStorageSync('offline-task-list');
  uni.removeStorageSync('offline-task-device');
  uni.removeStorageSync('offline-task-cache');
  uni.removeStorageSync('offline-task-detail');
  uni.removeStorageSync('offline-task-submit');
  uni.removeStorageSync('offline-task-fail');
  uni.removeStorageSync('offline-task-build');
}

// 开始离线上传
export const offlineUpload = async (address = "") => {
  let list = uni.getStorageSync("offline-task-submit") || [];
  for (let i = 0; i < list.length; i++) {
    const imgUrls = list[i].imgUrl;
    const promiseAll = [];
    const result = imgUrls.filter(url => url.includes("_doc"));
    for (let a = 0; a < result.length; a++) {
      const temp = result[a];
      const res = await uploadFilePromise(temp, address)
      if (res && res.code === 200) {
        const index = imgUrls.indexOf(temp);
        if (index !== -1) {
          imgUrls[index] = res.fileName;
        }
      }
      promiseAll.push(res);
    }
    await Promise.all(promiseAll)

    let params = Object.assign({}, list[i]);
    params.imgUrl = params.imgUrl.join(",");
    if (imgUrls.some((i) => i.indexOf("_doc") !== -1)) {
      removeSubmit(list[i]);
      saveFail({ ...list[i], imgUrl: imgUrls || [] }, '图片上传失败');
    } else {
      const response = await recordAdd(params, false);
      if (response && response.code === 200) {
        uni.$emit("listSelectStateTask");
        removeSubmit(list[i], response.data.isFinish);
      } else {
        removeSubmit(list[i]);
        saveFail({ ...list[i], imgUrl: imgUrls || [] });
      }
    };
  }
}

// 移除检查记录
const removeSubmit = (row, isFinish = false) => {
  let newList = uni.getStorageSync("offline-task-submit");
  newList = newList.filter(item => item.completeTime !== row.completeTime);
  uni.setStorage({
    key: "offline-task-submit",
    data: newList,
    success: () => {
      EventBus.emit("offlineChange", { key: 'offline-task-submit', data: newList, isFinish });
    }
  });
}

// 保存错误信息
const saveFail = (item, failReason = "网络异常") => {
  let fails = uni.getStorageSync("offline-task-fail");
  if (fails) {
    fails = fails.filter((i) => i.completeTime !== item.completeTime);
    fails.push({ ...item, failReason });
  } else {
    fails = [{ ...item, failReason }];
  }
  uni.setStorageSync("offline-task-fail", fails);
};

// 上传凭证图片
const uploadFilePromise = (url, address = "") => {
  return new Promise((resolve, reject) => {
    commonUpload(url, "/common/watermarkUpload", 'file', address)
      .then((res) => {
        if (res.code === 200) {
          resolve(res);
        } else {
          resolve(false);
        }
      })
      .catch(() => {
        resolve(false);
      });
  });
};

// 检测有无网络
export const checkNetwork = () => {
  return new Promise((resolve, reject) => {
    uni.getNetworkType({
      success: (res) => {
        let networkType = res.networkType;
        if (['2g', '3g', 'unknown', 'none'].includes(networkType)) {
          networkType = "none";
        }
        resolve(networkType)
      },
      fail: () => {
        resolve('none');
      }
    })
  })
}
